package com.shaozi.nc.data.mongodao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.shaozi.data.mongo.dao.SZMongoBaseDao;
import com.shaozi.nc.data.model.UserInfoModel;

@Repository("companyUserInfoMDao")
public class CompanyUserInfoMDao extends SZMongoBaseDao<UserInfoModel> {

	@Autowired
	public CompanyUserInfoMDao(MongoTemplate shaoziTemplate) {
		super(shaoziTemplate);
	}


	public UserInfoModel getUserInfo(String companyId, String uid) {
		Criteria c = new Criteria(UserInfoModel.FIELDNAME_companyId).is(companyId);
		c.and(UserInfoModel.FIELDNAME_uid).is(uid);
		Query query = new Query(c);
		return getMongoTemplate().findOne(query, UserInfoModel.class);
	}

	public List<UserInfoModel> getCompanyUserInfos(String companyId) {
		Criteria c = new Criteria(UserInfoModel.FIELDNAME_companyId).is(companyId);
		Query query = new Query(c);
		return getMongoTemplate().find(query, UserInfoModel.class);
	}
	
	public List<UserInfoModel> getCompanyUserInfos(String companyId,Integer isDel) {
		Criteria c = new Criteria(UserInfoModel.FIELDNAME_companyId).is(companyId);
		c.and(UserInfoModel.FIELDNAME_isDel).is(isDel);
		Query query = new Query(c);
		return getMongoTemplate().find(query, UserInfoModel.class);
	}

	public void upsertUserBean(UserInfoModel userinfo) {
		Criteria cri = new Criteria(UserInfoModel.FIELDNAME_companyId).is(userinfo.getCompanyId());
		cri.and(UserInfoModel.FIELDNAME_uid).is(userinfo.getUid());

		Update up = new Update();
		up.set(UserInfoModel.FIELDNAME_uid, userinfo.getUid());
		up.set(UserInfoModel.FIELDNAME_username, userinfo.getUsername());
		up.set(UserInfoModel.FIELDNAME_companyId, userinfo.getCompanyId());
		up.set(UserInfoModel.FIELDNAME_isDel, userinfo.getIsDel());

		getMongoTemplate().upsert(new Query(cri), up, UserInfoModel.class);
	}

	public void saveCompanyModel(Map<String, UserInfoModel> companyUserInfo) {
		for (Entry<String, UserInfoModel> entry : companyUserInfo.entrySet()) {
			upsertUserBean(entry.getValue());
		}
	}

	public void signUserInfoDeleted(String companyId, List<String> signeDeleted) {
		Criteria cri = new Criteria(UserInfoModel.FIELDNAME_companyId).is(companyId);
		cri.and(UserInfoModel.FIELDNAME_uid).in(signeDeleted);

		Update up = new Update();
		up.set(UserInfoModel.FIELDNAME_isDel, UserInfoModel.USERINFO_DELETED);

		getMongoTemplate().updateMulti(new Query(cri), up, UserInfoModel.class);
	}
}
